package hxg.tcptest.demo4;

import java.io.*;
import java.util.Properties;

/**
 * @author HeXiangGuang
 * @create 2021-06-30 21:54
 * 工具类
 */
public class Tools {
    //1加载属性文件
    public static Properties loadProperties(){
        //创建properties属性集合
        Properties properties = new Properties();
        //判断文件是否存在
        File file = new File("users.properties");
        if (file.exists()){
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                properties.load(fis);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                    if (fis !=null){
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
            }
        }
        return properties;
    }
    //2保存属性文件properties
    public static void saveProperties(String json){
        String[] infos = json.substring(1, json.length() - 1).split(",");
//        String[] split = infos[0].split(":");
//        String id = split[1];
        String id = infos[0].split(":")[1];
        //保存数据，并且不覆盖append 属性设置为true
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("users.properties", true);
            Properties properties = new Properties();
            properties.setProperty(id,json);
            properties.store(fos,"");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos !=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
